package com.gzz.mybatis.common.conditices.rule;

import com.gzz.orchid.common.core.util.StringUtil;
import lombok.Getter;

import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author higmd
 */
public abstract class AbstractRegular implements IRegular {
    // 字段名
    protected String fieldName;
    // 操作符号
    @Getter
    protected SqlSymbol symbol;
    // 前一个操作符号
    @Getter
    protected SqlSymbol previous;

    public AbstractRegular(String fieldName, SqlSymbol symbol, SqlSymbol previous) {
        this.fieldName = fieldName;
        this.symbol = symbol;
        this.previous = previous;
    }

    /**
     * 还原表达式
     */
    @Override
    public abstract String resolveExpression();

    /**
     * 格式化值
     */
    protected String formatterValue(Object value) {
        if(value instanceof Object[] valueArray){
           return Stream.of(valueArray)
                   .map(this::formatValue)
                    .collect(Collectors.joining(","));
        }else if(value instanceof Collection<?> valueCollection) {
          return  valueCollection.stream()
                    .map(this::formatValue)
                    .collect(Collectors.joining(","));
        }else{
            return formatValue(value);
        }
    }
    private String formatValue(Object value) {
        if(StringUtil.isNumeric(value)){
            return String.format("%s",value);
        }
        return String.format("'%s'", value);
    }
}
